<?php
/**
 * 飞信机器人--功能插件--投票
 * 功能：实现投票功能
 * 数据表：fx_vote_options,fx_vote_records
 * 作者： Kelvin
 * 联系： msn:shichangguo@msn.com, qq:191848423
*/
/*
支持参数(fx_menus表 extra_params字段)：
voteid=投票id&
start=2009-09-03&
end=2009-10-03&  开始时间&结束时间，请严格按要求来写
secret=1  是否保密投票（结果不公开）
repeat=1 是否允许重复投票
multi=1 是否允许多重投票
*/
/*
 数据表定义:
投票选项表：
CREATE TABLE `fx_vote_options` (
  `id` mediumint(10) NOT NULL auto_increment,
  `vote_id` mediumint(10) default NULL,
  `title` varchar(30) collate utf8_bin default NULL,
  `s_order` mediumint(10) default NULL,
  `ballots` int(5) default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

投票结果表：
CREATE TABLE `fx_vote_records` (
  `id` mediumint(10) NOT NULL auto_increment,
  `voter_id` varchar(12) collate utf8_bin NOT NULL,
  `vote_time` bigint(12) default NULL,
  `vote_id` mediumint(10) default NULL,
  `option_id` mediumint(10) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
*/

class Vote extends CommonPlugin
{
	var $UUID='1c6ee2d4-894f-42c8-8ea7-f272b766bcbc';
	
	public function Vote(&$session, $pid, $extraPara="")
	{
		parent::__construct($session, $pid, $extraPara);
	}
	
	public function getList($voteid,$showResult=false)
	{
		$msg = "<Font Face='宋体' Color='-8388608' Size='12.5'>";
		$msg.= $this->session->currentMenu['tips']."\n\n";
		$msg.= "</Font>";
		
		$msg.= "<Font Face='楷体' Color='-16744320' Size='10.5'>";
			
		$sql = "select * from fx_vote_options where vote_id=$voteid order by id";
		$retArr = $this->session->db->fetchQueryAll($sql);

		for($i=0; $i<count($retArr); $i++ )
		{
			if( $showResult )
			{
				$msg.="[".($i+1)."] ".$retArr[$i]['title']."(".$retArr[$i]['ballots']."票)\n";
			}else 
			{
				$msg.="[".($i+1)."] ".$retArr[$i]['title']."\n";
			}
		}
		
		$msg.="</Font>";
		return $msg;
	}
	public function getTips()
	{
		$voteid = $this->extraParam['voteid'];
		$start  = isset($this->extraParam['start'])?$this->extraParam['start']:"";
		$end    = isset($this->extraParam['end'])?$this->extraParam['end']:"";
		$secret = isset($this->extraParam['secret'])?$this->extraParam['secret']:0;
		$today = date('Y-m-d');
		
		if( $start != "" && $today<$start) return "投票活动尚未开始[开始时间:{$start}]\n". $this->getFooter();
		if( $end != "" && $today >$end )return "投票活动已经结束[结束时间:{$end}]\n". $this->getFooter();
		
		if( $secret==1 )
		{
			return $this->getList($voteid).$this->getFooter();
		}else 
		{
			return $this->getList($voteid).$this->getFooter(',v-查看投票结果');
		}
	}
	
	public function doVote($voteid,$inputArr,$secret=false)
	{
		$allowRepeat = $this->extraParam['repeat'];
		
		if( !$allowRepeat )	//不允许重复投票
		{
			// 首先判断是否已经投票
			$sql = "select count(*) as count from fx_vote_records where voter_id={$this->session->buddyID} and vote_id={$voteid}";
			$retArr = $this->session->db->fetchQueryAll($sql);
			if($retArr[0]['count'] > 0 )
			{
				return "您已经投过票,不允许重复投票！\n".$this->getFooter();
			}
		}
		
		//
		$sql = "select * from fx_vote_options where vote_id=$voteid order by id";
		$retArr = $this->session->db->fetchQueryAll($sql);

		for($k=0; $k<count($inputArr); $k++ )
		{
			$input = $inputArr[$k];
			
			$optionid=0;
			for($i=0; $i<count($retArr); $i++ )
			{
				if( ($i+1) == intval($input) )
				{
					$optionid = $retArr[$i]['id'];
					break;
				}
			}
			if( $optionid == 0 )
			{
				//return "错误的选择，请重新输入\n".$this->getFooter(',输入数字投票');
				continue;
			}
			$time = time(NULL);
			$sql = "insert into fx_vote_records(voter_id,vote_time,vote_id,option_id) values({$this->session->buddyID},{$time},{$voteid},{$optionid})";
			$this->session->db->execute($sql);
			$this->session->db->execute("update fx_vote_options set ballots=ballots+1 where id={$optionid}");
		}
		if( !$secret )
			return "谢谢您的投票\n".$this->getFooter(',v--查看结果');
		else
			return "谢谢您的投票\n".$this->getFooter('');
	}

	public function handle($input)
	{
		if( parent::handleInput($input)) return false;
	
		$voteid = $this->extraParam['voteid'];
		$start  = isset($this->extraParam['start'])?$this->extraParam['start']:"";
		$end    = isset($this->extraParam['end'])?$this->extraParam['end']:"";
		$secret = isset($this->extraParam['secret'])?$this->extraParam['secret']:0;
		$today = date('Y-m-d');

		// 检查时间
		if( $start != "" && $today<$start) return "投票活动尚未开始[开始时间:{$start}]\n". $this->getFooter();
		if( $end != "" && $today >$end )return "投票活动已经结束[结束时间:{$end}]\n". $this->getFooter();
					
		if( $input == 'v' )	//查看结果
		{
			if($secret == 1)
			{
				return "该投票为保密投票，结果不对外！\n".$this->getFooter();
			}
			return $this->getList($voteid,true).$this->getFooter();
		}
		
		$inputArr = explode(',',$input);
		for($i = 0; $i<count($inputArr); $i++ )
		{
			if(!is_numeric($inputArr[$i]))return "错误指令\n".$this->getFooter();
		}
		
		$allowMulti =  $this->extraParam['multi'];
		if(count($inputArr)>1 && !$allowMulti )return "不支持多选".$this->getFooter();
		
		return $this->doVote($voteid,$inputArr,$secret);
	}
	
	/*public static function timer($svcMobile,$tick)
	{
		echo "Vote timer:$svcMobile,$tick\n";
	}*/
}
?>